package com.fengye.middleware.rabbitmq.boot.messageType.topic;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author sky
 * @date 2021年06月09日 1:32 下午
 */
@Component
@Slf4j
public class TopicPublisher {

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.topic.exchange.name:topic_change_name}")
    private String topicExchangeName;

    public void sendObjectMsg(String msg, String routingKey) {
        if (StringUtils.hasText(msg) && StringUtils.hasText(routingKey)) {
            try {
                rabbitTemplate.setMessageConverter(new SimpleMessageConverter());
                rabbitTemplate.setExchange(topicExchangeName);
                rabbitTemplate.setRoutingKey(routingKey);
                Message message = MessageBuilder.withBody(msg.getBytes(StandardCharsets.UTF_8)).build();
                rabbitTemplate.convertAndSend(message);

                log.info("消息模型 TopicExchange：生产者-发送对象类型的消息：{} , routingKey= {}", msg, routingKey);
            } catch (Exception e) {
                log.error("消息模型 TopicExchange：生产者-发送消息异常：{}, routingKey= {}", msg, routingKey, e.fillInStackTrace());
            }
        }
    }

}
